const inquirer = require('inquirer')

const { errorLog } = require('../utils')

const config = require(`${process.cwd()}/deploy.config.js`)

const inputPwd = async () => {
  const data = await inquirer.prompt([
    {
      type: 'password',
      name: 'password',
      message: '服务器密码'
    }
  ])
  return data.password
}

// 检查配置文件
const checkConfig = (conf) => {
  const checkArr = Object.entries(conf)
  checkArr.map((it) => {
    const key = it[0]
    if (key === 'servicePath' && conf[key] === '/') {
      // 上传zip前会清空目标目录内所有文件
      errorLog('PATH 不能是服务器根目录!')
      process.exit()
    }
    if (!conf[key] && !['script'].includes(key)) {
      errorLog(`配置项 ${key} 不能为空`)
      process.exit()
    }
  })
}

const environment = async () => {
  let envConfig = null
  if (config.length === 1) {
    envConfig = config[0]
  } else {
    const data = await inquirer.prompt([
      {
        type: 'list',
        message: '请选择发布环境',
        name: 'env',
        choices: config.map((sever) => ({
          name: sever.name,
          value: sever.name
        }))
      }
    ])
    envConfig = config.find((server) => data.env === server.name)
  }

  if (envConfig) {
    if (envConfig.privateKey) {
      delete envConfig.password
    } else if (!envConfig.password) {
      envConfig.password = await inputPwd()
    }

    if (envConfig.password) {
      delete envConfig.privateKey
    }
    checkConfig(envConfig)
    return envConfig
  } else {
    errorLog('未找到该环境')
    process.exit()
  }

}

module.exports = environment
